<template>
  <div class="params">
    <div class="params_top">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card>
      <el-alert
        show-icon
        :closable="false"
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
      ></el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:&nbsp;&nbsp;&nbsp;</span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="catelist"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            class="addparam"
            @click="adddialogVisible = true"
            :disabled="isbtndis"
            type="primary"
            size="mini"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  @close="tagclosed(index, scope.row)"
                  closable
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="showEdit(scope.row.attr_id)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  @click="removeEdit(scope.row.attr_id)"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            class="addparam"
            @click="adddialogVisible = true"
            :disabled="isbtndis"
            type="primary"
            size="mini"
            >添加属性</el-button
          >

          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  @close="tagclosed(index, scope.row)"
                  closable
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="showEdit(scope.row.attr_id)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  @click="removeEdit(scope.row.attr_id)"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      @close="addclosed"
      :title="'添加' + titleText"
      :visible.sync="adddialogVisible"
      width="50%"
    >
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      @close="editclosed"
      :title="'修改' + titleText"
      :visible.sync="editdialogVisible"
      width="50%"
    >
      <el-form
        :model="editForm"
        :rules="addFormrules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "Params",
  components: {},
  data() {
    return {
      catelist: [],
      selectedCateKeys: [],
      activeName: "many",
      manyTableData: [],
      onlyTableData: [],
      adddialogVisible: false,
      editdialogVisible: false,
      addForm: {
        attr_name: "",
      },
      editForm: {
        attr_name: "",
      },
      addFormrules: {
        attr_name: [
          { required: true, message: "此选项不能为空！", trigger: "blur" },
        ],
      },
    };
  },

  computed: {
    isbtndis() {
      if (this.selectedCateKeys.length != 3) {
        return true;
      }
      return false;
    },
    cateId() {
      if (this.selectedCateKeys.length == 3) {
        return this.selectedCateKeys[2];
      }
      return null;
    },
    titleText() {
      if (this.activeName == "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },

  created() {
    this.getCateList();
  },

  methods: {
    getCateList() {
      this.$http.get(`categories`).then((res) => {
        console.log(res);
        if (res.meta.status != 200) {
          return this.$message.error("获取商品 分类失败");
        }
        // this.$message.sussess("获取商品分类成功!");
        this.catelist = res.data;
      });
    },
    handleChange() {
      this.getParamsData();
    },
    // tab
    handleClick() {
      this.getParamsData();
    },

    getParamsData() {
      if (this.selectedCateKeys.length != 3) {
        this.selectedCateKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      this.$http
        .get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: this.activeName,
          },
        })
        .then((res) => {
          if (res.meta.status != 200) {
            return this.$message.error("获取参数列表失败!");
          }
          this.$message.success("获取参数列表成功！");
          res.data.forEach((item) => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
            item.inputVisible = false;
            item.inputValue = "";
          });
          if (this.activeName == "many") {
            this.manyTableData = res.data;
          } else {
            this.onlyTableData = res.data;
          }
        });
    },
    addclosed() {
      this.$refs.addFormRef.resetFields();
    },
    addParams() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return;
        this.$http
          .post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          })
          .then((res) => {
            if (res.meta.status != 201) {
              return this.$message.error("添加数据失败！");
            }
            this.$message.success("添加数据成功！");
            this.adddialogVisible = false;
            this.getParamsData();
          });
      });
    },
    showEdit(id) {
      this.$http
        .get(
          `categories/${this.cateId}/attributes/${id}`,
          {},
          {
            params: { attr_sel: this.activeName },
          }
        )
        .then((res) => {
          if (res.meta.status != 200) {
            return this.$message.error("获取数据失败！");
          }
          this.$message.success("获取数据成功！");
          this.editForm = res.data;
          this.editdialogVisible = true;
        });
    },
    editclosed() {
      this.$refs.editFormRef.resetFields();
    },

    editParams() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        this.$http
          .put(
            `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
            {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName,
            }
          )
          .then((res) => {
            if (res.meta.status != 200) {
              return this.$message.error("修改数据失败！");
            }
            this.$message.success("修改数据成功！");
            this.editdialogVisible = false;
            this.getParamsData();
          });
      });
    },
    removeEdit(id) {
      this.$confirm("此操作将永久删除该参数/属性, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
       
      this.$http
        .delete(`categories/${this.cateId}/attributes/${id}`)
        .then((res) => {
          if (res.meta.status != 200) {
            return this.$message.error("删除参数/属性失败！");
          }
          this.getParamsData();

          this.$message({
            type: "success",
            message: "删除参数/属性成功!",
          });
        });
    },
    // 文本框触发
    handleInputConfirm(row) {
      if (row.inputValue.trim().length == 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals(row);
    },
    showInput(row) {
      row.inputVisible = true;

      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    tagclosed(index, row) {
      row.attr_vals.splice(index, 1);
      this.saveAttrVals(row);
    },
    saveAttrVals(row) {
      this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(" "),
      }).then((res) => {
        if (res.meta.status != 200) {
          return this.$message.error("修改参数项失败！");
        }
        this.$message.success("修改参数项成功！");
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-cascader {
  margin-left: 5px;
  width: 300px;
}
span {
  font-size: 14px;
}
.addparam {
  margin-bottom: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
.params_top {
  width: 100%;
  height: 40px;
}
</style>
